﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CardMonitor.Controls
{
    /// <summary>
    /// LicensePlateKeyboard.xaml 的交互逻辑
    /// </summary>
    public partial class LicensePlateKeyboard : UserControl
    {
        public LicensePlateKeyboard()
        {
            InitializeComponent();
            DataContext = this;

        }
        private TextBox _targetTextBox;
        public TextBox TargetTextBox
        {
            get => _targetTextBox;
            set
            {
                _targetTextBox = value;
                OnPropertyChanged();
            }
        }

        // 命令定义
        public ICommand KeyPressCommand => new RelayCommand<string>(AppendText);
        public ICommand DeleteCommand => new RelayCommand(DeleteLastChar);
        public ICommand ClearCommand => new RelayCommand(ClearText);
        public ICommand ConfirmCommand => new RelayCommand(Confirm);

        /// <summary>
        /// 向目标文本框追加字符
        /// </summary>
        private void AppendText(string character)
        {
            if (TargetTextBox == null || string.IsNullOrEmpty(character)) return;

            // 获取当前光标位置
            int caretIndex = TargetTextBox.CaretIndex;

            // 在光标位置插入字符
            TargetTextBox.Text = TargetTextBox.Text.Insert(caretIndex, character);

            // 移动光标到新位置
            TargetTextBox.CaretIndex = caretIndex + character.Length;

            // 确保文本框保持焦点
            TargetTextBox.Focus();
        }

        /// <summary>
        /// 删除光标前的字符
        /// </summary>
        private void DeleteLastChar()
        {
            if (TargetTextBox == null || string.IsNullOrEmpty(TargetTextBox.Text)) return;

            // 如果有选中文本，删除选中部分
            if (TargetTextBox.SelectionLength > 0)
            {
                TargetTextBox.SelectedText = "";
                return;
            }

            // 删除光标前的字符
            int caretIndex = TargetTextBox.CaretIndex;
            if (caretIndex > 0)
            {
                TargetTextBox.Text = TargetTextBox.Text.Remove(caretIndex - 1, 1);
                TargetTextBox.CaretIndex = caretIndex - 1;
            }

            TargetTextBox.Focus();
        }

        /// <summary>
        /// 清空目标文本框
        /// </summary>
        private void ClearText()
        {
            if (TargetTextBox != null)
            {
                TargetTextBox.Text = "";
                TargetTextBox.Focus();
            }
        }

        /// <summary>
        /// 确认输入并关闭键盘
        /// </summary>
        private void Confirm()
        {
            // 从父容器中移除键盘
            if (Parent is Panel parentPanel)
            {
                parentPanel.Children.Remove(this);
            }
            else if (Parent is ContentControl contentControl)
            {
                contentControl.Content = null;
            }

            // 将焦点返回给目标文本框
            TargetTextBox?.Focus();
        }

        #region INotifyPropertyChanged 实现
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }

    #region RelayCommand 实现
    public class RelayCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        public RelayCommand(Action execute, Func<bool> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;

        public void Execute(object parameter) => _execute();

        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }

    public class RelayCommand<T> : ICommand
    {
        private readonly Action<T> _execute;
        private readonly Func<T, bool> _canExecute;

        public RelayCommand(Action<T> execute, Func<T, bool> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter) =>
            _canExecute?.Invoke((T)parameter) ?? true;

        public void Execute(object parameter) =>
            _execute((T)parameter);

        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }
    #endregion
}

